package com.cyy.vue.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MyUtils {

    /**
     * 过期时间15分钟
     */
    private static final long EXPIRE_TIME = 15 * 60 * 1000;

    /**
     * token私钥
     */
    private static final String TOKEN_SECRET = "b5db36b605a0b4a8f5121e6f62858aaa";

    /**
     * 生成token
     */
    public static String sign(String userName,Long userId){
        try {
            Date date = new Date(System.currentTimeMillis()+ EXPIRE_TIME);
            //私钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String,Object> header = new HashMap<>();
            header.put("type","jwt");
            header.put("alg","HS256");
            //附带username,userId等信息，生成签名
            return JWT.create()
                    .withHeader(header)
                    .withClaim("userName",userName)
                    .withClaim("userId",userId)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }

    }
}
